
package com.itheima.controller.backend.security;

import com.itheima.mapper.MenuMapper;
import com.itheima.mapper.RoleMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SpringSecurityUserService implements UserDetailsService {
    //查找服务，实现查询数据库
//    @Autowired
//    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;

    //根据用户名查询数据库中用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.getByUsername(username);
        if(user == null){
            throw  new UsernameNotFoundException("用户不存在");
        }
        //查询当前用户对应的角色和权限
        List<Role> roles = userMapper.getRolesByUserId(user.getId());
        for (Role role : roles) {
            Set<Permission> permissions = roleMapper.getPermissionsByRoleId(role.getId());
            role.setPermissions(permissions);
            LinkedHashSet<Menu> menus = menuMapper.getMenusByRoleId(role.getId()) ;
            role.setMenus(menus);
        }
        String[] roleArray = roles.stream()
                .map(Role::getPermissions)
                .collect(Collectors.toList())
                .toArray(new String[0]);
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(roleArray);
        UserVO userVO = UserVO.builder()
                .username(username)
                .password(user.getPassword())
                .authorities( authorities)
                .build();
        return userVO;
    }
}

